#include<stdio.h>
#include "../include/N_arytree.h"
#include "../include/errorcodes.h"


void add_for_copyFile(char *dirName, char *fileName, char *filePath)
{
		int isFileFull = 1;             //to keep track if the bitarray is full
		
		int isValid=checkNameValidity(fileName);
		if(isValid==0)
		{
			printf("copyfile_FAILURE <%s>", ERR_VFS_ADDFILE_08);
			return;
		}
		
		flist bitArray[header.maxNoOfFileDescriptor];
		int index=0,i=0,file_offset=0;
		int eof=-1,result=0,fsize=0, blockNo;
		char ch='0';

		fd* sourceFileDesc = bstSearchNode(&bstRoot,filePath);
		int sourceFileBNo = sourceFileDesc->blockNum;

		FILE *fptr=fopen(header.fileSystemLabel,"rb+");
		char sourceContent[1024];
		

		//create file descriptor
		fd *new=(fd *) malloc(sizeof(fd));
		new->fileType='F';
		strcpy(new->file_name, fileName);
		strcpy(new->path, dirName);

		if(fptr==NULL) {
			printf("copyfile_FAILURE <%s>", ERR_VFS_ADDFILE_08);
			return;
		}
		else {
			while(ch!='!') {
				fread(&ch,sizeof(ch),1,fptr);
				file_offset++;
			}

			fseek(fptr,(file_offset+(sourceFileBNo*1024)),SEEK_SET);
			i=0;
			char readChars;
			while((readChars = fgetc(fptr)) != EOF) {
				sourceContent[i] = readChars;
				i++;
				//fputc(readChars, destPtr);
			}
			fsize = i;
						
			//search the freelist for empty block;write block in file block.
		
			
			fseek(fptr,31,SEEK_SET);
			fread(bitArray,sizeof(flist),header.maxNoOfFileDescriptor,fptr);
			
			for(i=0;i<header.maxNoOfFileDescriptor;i++)
			{
				if(bitArray[i].value == '0')
				{
					//printf("\nIn if set\n");
					bitArray[i].value='1';
					isFileFull = 0;
					break;
				}
			}
			blockNo = i;
			
			if(isFileFull == 1)
			{
				printf("copyfile_FAILURE <%s>", ERR_VFS_ADDFILE_08);
				return;
			}
		
			fseek(fptr,(file_offset+(i*1024)),SEEK_SET);

			i=0;
			while(i<fsize) {
				//printf("%c", sourceContent[i]);
				fputc(sourceContent[i], fptr);
				i++;
			}
			fputc(EOF, fptr);
			//printf("\n*********************************\n");
			
		}
		
		new->blockNum = blockNo;
		new->fileSize = fsize;


		//insert file descriptor in the narray,hashtable and binarytree

		int insert=insert_node(&naryRoot,new);
		//printf("Insert status=%d\n",insert);
		//printtree(naryRoot);
		bstInsertNode(&bstRoot,new);
		//print(bstRoot);
		hashInsert(hash,*new);


		fseek(fptr,31,SEEK_SET);
		fwrite(bitArray,sizeof(flist),header.maxNoOfFileDescriptor,fptr);

		fclose(fptr);
		
}
